/**
 * Created with IntelliJ IDEA.
 * Description: 牛客网: BM83 字符串变形
 * <a href="https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e?tpId=295&tqId=44664&ru=/exam/company&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Fcompany">...</a>
 * User: DELL
 * Date: 2023-06-01
 * Time: 23:29
 */
public class Solution {
    /**
     * 解题思路: (双逆序)
     * 先将原字符串逆序,之后在针对每一个单词进行逆序即可,同时要注意处理最后一个单词,
     * 因为最后一个单词的末尾可能没有空格.
     * @param s
     * @param n
     * @return
     */
    public String trans(String s, int n) {
        StringBuilder str = new StringBuilder();
        //进行大小写转换
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            if  (ch == ' ') {
                str.append(' ');
            } else if (ch >= 'a' && ch <= 'z') {
                str.append((char)(ch-32));
            } else {
                str.append((char)(ch+32));
            }
        }
        //先对整个字符串进行逆序
        str.reverse();
        //对其中的每个单词进行逆序
        int left = 0;
        for (int i = 0; i < n; i++) {
            if (str.charAt(i) == ' ') {
                StringBuilder builder = new StringBuilder(str.substring(left,i));
                String temp = builder.reverse().toString();
                str.replace(left,i,temp);
                left = i+1;
            }
        }
        //处理最后一个单词
        if (str.charAt(n-1) != ' ') {
            StringBuilder builder = new StringBuilder(str.substring(left,n));
            String temp = builder.reverse().toString();
            str.replace(left,n,temp);
        }
        return str.toString();
    }
}